<template>
  <!-- 设备信息表单弹窗 -->
  <el-dialog
    :close-on-click-modal="false"
    v-model="visibleDialog"
    :title="props.title"
    width="800px"
    style="min-height: 500px"
    draggable
    @close="closeDialog"
    destroy-on-close
  >
    <el-form ref="formRef" :model="formData" label-width="90">
      <el-row>
        <el-col :span="8">
          <el-form-item label="设备编号" prop="equipCode">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipCode"
              placeholder="请输入参数名"
              disabled
              clearable
            />
            <span v-else>{{ formData.equipCode }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备名称" prop="equipName">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.equipName"
              placeholder="请输入地址"
              clearable
              disabled
            />
            <span v-else>{{ formData.equipName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="设备类型" prop="name">
            <el-input
              v-if="!props.isReadonly"
              v-model="formData.name"
              placeholder="请输入地址"
              clearable
              disabled
            />
            <span v-else>{{ formData.name }}</span>
          </el-form-item>
        </el-col>
      </el-row>
      <el-checkbox style="margin: 10px 0" v-model="checked1"
        >数据完整时采集</el-checkbox
      >
      <div>注：只有设置有效规则的参数才能显示在下表</div>
      <el-table :data="filtered" border style="width: 100%; min-height: 100px">
        <el-table-column prop="parameterName" label="参数名" width="180" />
        <el-table-column prop="parameterDesc" label="参数描述" width="180" />
        <el-table-column prop="validationRuleType" label="有效规则">
          <template #default="scope">
            {{ useDictionary("ScaDataRule", scope.row.validationRuleType) }}
          </template>
        </el-table-column>
      </el-table>
      <el-checkbox style="margin: 10px 0" v-model="checked2"
        >数据防重复校验</el-checkbox
      >
      <el-form-item label-width="0">
        <el-select
          v-model="formData.dataPrimaryKey"
          multiple
          placeholder="请选择参数"
          style="width: 100%"
        >
          <el-option
            v-for="item in formDataCollectList"
            :key="`${item.id}`"
            :label="`${item.parameterName}-${item.parameterDesc}`"
            :value="`${item.id}`"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
defineOptions({
  name: "SCAEQUIPINFOCONTENTEDIT",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible1"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);

watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const rules = reactive({
  version: [],
  equipCode: [{ required: true, message: "请输入设备编号", trigger: "blur" }],
  equipName: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  equipModel: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  ipAddress: [
    { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData: any = reactive({
  id: "",
  version: "",
  equipCode: "",
  equipName: "",
  equipModel: "",
  ipAddress: "",
  imgUrl: "",
  threeModelUrl: "",
  equipTypeId: "",
  equipTypeCode: "",
  equipTypeName: "",
  equipStatus: "",
  equipStatusName: "",
  locationId: "",
  enabled: 1,
  deleted: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  name: "",
  isVerifyDataIntegrity: 0,
  isVerifyDataRepeat: 0,
  dataPrimaryKey: "" || [],
});
let formDataCollectList: any = ref([
  {
    deleted: 0,
    enabled: 0,
    enumValueList: "",
    enumerationValue: "",
    id: "",
    ids: [],
    lowerLimitValue: "",
    maxValue: "",
    measurementUnit: "",
    minValue: "",
    parameterDesc: "",
    parameterName: "",
    parameterType: "",
    relationId: "",
    relationType: "",
    remarks: "",
    roleType: "",
    showType: "",
    sort: "",
    upperLimitValue: "",
    url: "",
    validationRuleType: "",
    version: "",
    value: "",
    label: "",
  },
]);

let filtered = ref([]);
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      formData.name = `${formData.equipTypeCode}-${formData.equipTypeName}`;
      formDataCollectList.value = newVal.scaEquipCollectionParams;
      //  ` formDataCollectList.value.map((item: any) => {
      //     item.label = `${item.parameterName}`;
      //     item.value = `${item.id}`;
      //   });`
      filtered.value = formDataCollectList.value.filter(function (item: any) {
        return item.validationRuleType != "";
      });
      checked1.value = formData.isVerifyDataIntegrity === 1 ? true : false;
      checked2.value = formData.isVerifyDataRepeat === 1 ? true : false;
      formData.dataPrimaryKey = formData.dataPrimaryKey
        ? formData.dataPrimaryKey.split(",")
        : [];
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible1", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.equipModel = "";
  formData.ipAddress = "";
  formData.imgUrl = "";
  formData.threeModelUrl = "";
  formData.equipTypeId = "";
  formData.equipTypeCode = "";
  formData.equipTypeName = "";
  formData.equipStatus = "";
  formData.equipStatusName = "";
  formData.locationId = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.scaEquipcollectionParams = [
    {
      deleted: 0,
      enabled: 0,
      enumValueList: "",
      enumerationValue: "",
      id: "",
      ids: [],
      lowerLimitValue: "",
      maxValue: "",
      measurementUnit: "",
      minValue: "",
      parameterDesc: "",
      parameterName: "",
      parameterType: "",
      relationId: "",
      relationType: "",
      remarks: "",
      roleType: "",
      showType: "",
      sort: "",
      upperLimitValue: "",
      url: "",
      validationRuleType: "",
      version: "",
    },
  ];
  formData.name = "";
  formData.isVerifyDataIntegrity = 0;
  formData.isVerifyDataRepeat = 0;
  formData.dataPrimaryKey = [];
  formDataCollectList.value = [];
  filtered.value = [];

  checked1.value = false;
  checked2.value = false;
}

const checked1 = ref(false);
const checked2 = ref(false);

const loading = ref(false);

/** 设备信息保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      formData.isVerifyDataIntegrity = checked1.value === true ? 1 : 0;
      formData.isVerifyDataRepeat = checked2.value === true ? 1 : 0;
      formData.dataPrimaryKey = formData.dataPrimaryKey.toString();
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/iotadmin/scaequipinfo/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible1", false);
});
</script>
<style lang="scss" scoped></style>
